package com.heba.greenmulu.scan;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.adapter.category.CategoryExpandableAdapter;
import com.heba.bean.category.CategoryLevel2Object;
import com.heba.bean.category.CategoryLevel3Object;
import com.heba.bean.category.ItemCategoryObject;
import com.heba.bean.expandgroup.DataListTree;
import com.heba.bean.product.ItemProductKeyWordObject;
import com.heba.bean.product.ProductCategory;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.ClearEditTextView;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 產品分類
 * Created by jason on 2020/1/8.
 */
public class ItemProductCategoryActivity extends BaseActivity {

    private ClearEditTextView clearEditTextView;
    private TextView tv_cancel;

    /**
     * 搜索view
     */
    private View search_view;
    private TextView tv_search_name;
    private TextView tv_category;
    private RecyclerView rv_search_view;
    private QuickAdapter searchAdapter;

    /**
     * 分类view
     */
    private RecyclerView rv_left;
    private RecyclerView rv_right;
    private RecyclerView rv_right2;
    private QuickAdapter leftAdapter;
    private QuickAdapter right2Adapter;

    /**
     * 分类二級列表adapter
     */
    private CategoryExpandableAdapter categoryExpandableAdapter;

    /**
     * 二级分类列表数据
     */
    private List<DataListTree<CategoryLevel2Object, CategoryLevel3Object>> mDataListTrees;

    /**
     * 所有分类数据
     */
    private List<ItemCategoryObject> categoryObjects;

    /**
     * 熱門關鍵詞
     */
    private List<ItemProductKeyWordObject> hotKeyWordList;

    /**
     * 搜索的产品分类
     */
    private List<ProductCategory> productCategories;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_category);
        findViewById();
        initView();
        setupClearEditTextView();
        getCategoryListData();
    }

    @Override
    protected void findViewById() {
        clearEditTextView = findViewById(R.id.clearEditText);
        tv_cancel = findViewById(R.id.txt_right);
        search_view = findViewById(R.id.search_view);
        tv_search_name = findViewById(R.id.tv_search_name);
        tv_category = findViewById(R.id.tv_category);
        rv_search_view = findViewById(R.id.rv_view);
        rv_left = findViewById(R.id.rv_left);
        rv_right = findViewById(R.id.rv_right);
        rv_right2 = findViewById(R.id.rv_right2);
    }

    @Override
    protected void initView() {
        categoryObjects = new ArrayList<>();
        mDataListTrees = new ArrayList<>();

        List<Integer> isCheck = new ArrayList<>();
        //默认选中第一个item
        isCheck.add(0);

        hotKeyWordList = new ArrayList<>();
        productCategories = new ArrayList<>();

        leftAdapter = new QuickAdapter<ItemCategoryObject>(categoryObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_category_product;
            }

            @Override
            public void convert(VH holder, ItemCategoryObject data, int position) {
                ImageView iv_icon = holder.getView(R.id.iv_icon);
                TextView tv_category = holder.getView(R.id.tv_category);
                tv_category.setText(data.getCategoryName());

                if (data.getCategoryName().equals(getResources().getString(R.string.scan_hot))) {
                    //加载本地资源图片
                    Glide.with(ItemProductCategoryActivity.this).load(R.drawable.icon_good).into(iv_icon);
                } else {
                    //加载网络图片
                    GlideUtil.loadImageWithDefaultPlaceHolder(ItemProductCategoryActivity.this, data.getIcon(), iv_icon);
                }

                List<CategoryLevel2Object> level2Objects = data.getCategoryLevel2();

                holder.itemView.setSelected(false);
                if (isCheck.contains(position)) {
                    holder.itemView.setSelected(true);
                    if (position == 0) {
                        rv_right.setVisibility(View.GONE);
                        rv_right2.setVisibility(View.VISIBLE);
                    } else {
                        rv_right.setVisibility(View.VISIBLE);
                        rv_right2.setVisibility(View.GONE);
                        mDataListTrees.clear();
                        for (int i = 0; i < level2Objects.size(); i++) {
                            CategoryLevel2Object object = level2Objects.get(i);
                            mDataListTrees.add(new DataListTree<>(object, object.getCategoryLevel3()));
                        }
                        categoryExpandableAdapter.setData(mDataListTrees);
                        categoryExpandableAdapter.notifyDataSetChanged();
                    }
                } else {
                    holder.itemView.setSelected(false);
                }

                /**
                 * 更新选中的item
                 */
                holder.itemView.setOnClickListener(v -> {
                    if (isCheck.contains(position))
                        return;
                    isCheck.clear();
                    isCheck.add(position);
                    notifyDataSetChanged();

                    if (!hotKeyWordList.isEmpty() && isCheck.contains(0)) {
                        rv_right2.setVisibility(View.VISIBLE);
                    } else {
                        /**
                         * 更新二级分类数据
                         */
                        rv_right2.setVisibility(View.GONE);
                        mDataListTrees.clear();
                        for (int i = 0; i < level2Objects.size(); i++) {
                            CategoryLevel2Object object = level2Objects.get(i);
                            mDataListTrees.add(new DataListTree<>(object, object.getCategoryLevel3()));
                        }
                        categoryExpandableAdapter.setData(mDataListTrees);
                        categoryExpandableAdapter.notifyDataSetChanged();
                    }
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        rv_left.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        rv_left.setAdapter(leftAdapter);

        /**
         * 二級列表recyclerview佈局設置
         */
        categoryExpandableAdapter = new CategoryExpandableAdapter(this);
        categoryExpandableAdapter.setData(mDataListTrees);
        rv_right.setLayoutManager(new LinearLayoutManager(this));
        rv_right.setAdapter(categoryExpandableAdapter);

        /**
         * 热门关键词列表
         */
        right2Adapter = new QuickAdapter<ItemProductKeyWordObject>(hotKeyWordList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_category_hot_textview;
            }

            @Override
            public void convert(VH holder, ItemProductKeyWordObject data, int position) {
                ImageView iv_icon = holder.getView(R.id.iv_icon);
                holder.setText(R.id.textview, data.getKeywordName());
                iv_icon.setVisibility(View.VISIBLE);
                GlideUtil.loadImageWithDefaultPlaceHolder(ItemProductCategoryActivity.this, data.getIcon(), iv_icon);

                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, data.getKeywordName());
                    bundle.putString(CommonConfig.PRODUCT_HOT_KEYWORD, data.getKeywordName());
                    openActivity(ItemProductSearchResultActivity.class, bundle);
                });
            }

        };
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        rv_right2.setLayoutManager(layoutManager1);
        rv_right2.setAdapter(right2Adapter);

        /**
         * 搜索分类adapter
         */
        searchAdapter = new QuickAdapter<ProductCategory>(productCategories) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_category_hot_textview;
            }

            @Override
            public void convert(VH holder, ProductCategory data, int position) {
                SpannableString s = CommonUtils.matcherSearchText(ItemProductCategoryActivity.this,
                        calculateCategoryString(data), clearEditTextView.getText());
                TextView textView = holder.getView(R.id.textview);
                textView.setText(s);

                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt(CommonConfig.CATEGORY_ID, data.getCategoryid());
                    bundle.putInt(CommonConfig.CATEGORY_LEVEL, data.getCategorylevel());
                    bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, getResources().getString(R.string.scan_category));
                    openActivity(ItemProductSearchResultActivity.class, bundle);
                });
            }

        };
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        rv_search_view.setLayoutManager(layoutManager2);
        rv_search_view.setAdapter(searchAdapter);

    }

    /**
     * 设置edittext
     */
    private void setupClearEditTextView() {
        clearEditTextView.setTextHint(this.getResources().getString(R.string.scan_search));

        /**
         * 搜索關鍵詞
         */
        //点击edittex跳转
        clearEditTextView.clearFocus();
        clearEditTextView.setOnEditTextListener(new ClearEditTextView.OnEditTextListener() {
            @Override
            public void onDeleteClick() {
                search_view.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(String text) {
                getSearchCategoryData(text);
            }

            @Override
            public void onSearchClick(String text) {
                openSearchResultAct(text);
            }

            @Override
            public void onIntent() {
                openActivity(ItemScanSearchActivity.class);
            }
        });

        tv_cancel.setOnClickListener(v -> finishActivity());
    }

    /**
     * 獲取分類數據
     */
    private void getCategoryListData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        client.get(Cfg.BaseUrl + "/Product/CategoryList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        categoryObjects.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemCategoryObject> objects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemCategoryObject>>() {
                                }.getType());
                                categoryObjects.addAll(categoryObjects.size(), objects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        /**
//                         * 刷新列表數據
//                         */
//                        recycleAdapter.notifyDataSetChanged();

                        /**
                         * 获取热门关键词
                         */
                        getKeyWordData();

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 獲取熱門關鍵詞數據
     */
    private void getKeyWordData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        client.get(Cfg.BaseUrl + "/Product/HotKeywords", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        hotKeyWordList.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemProductKeyWordObject> keyWordObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemProductKeyWordObject>>() {
                                }.getType());
                                hotKeyWordList.addAll(hotKeyWordList.size(), keyWordObjects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        updateCategoryList();

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 更新分类数据
     * 添加显示热门关键词
     */
    private void updateCategoryList() {
        if (!hotKeyWordList.isEmpty()) {
            ItemCategoryObject object = new ItemCategoryObject();
            object.setCategoryName(this.getResources().getString(R.string.scan_hot));
            categoryObjects.add(0, object);
            leftAdapter.notifyDataSetChanged();
            right2Adapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取分类搜索列表
     */
    private void getSearchCategoryData(String word) {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Keyword", word);
        client.get(Cfg.BaseUrl + "/Product/KeywordCategory", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        productCategories.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ProductCategory> objects = new Gson().fromJson(array.toString(), new TypeToken<List<ProductCategory>>() {
                                }.getType());
                                productCategories.addAll(productCategories.size(), objects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 更新数据
                         */
                        updateSearchView();

                    }

                    public void Failure() {
                        super.Failure();
                    }

                });
    }

    /**
     * 更新search View
     */
    private void updateSearchView() {
        search_view.setVisibility(View.VISIBLE);
        tv_search_name.setText(Html.fromHtml(String.format(getResources().getString(R.string.scan_product_search), clearEditTextView.getText())));
        searchAdapter.notifyDataSetChanged();

        tv_search_name.setOnClickListener(v -> {
            openSearchResultAct(clearEditTextView.getText());
        });
    }

    /**
     * 跳轉搜索結果頁面
     *
     * @param text
     */
    private void openSearchResultAct(String text) {
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, text);
        bundle.putString(CommonConfig.PRODUCT_KEYWORD, text);
        openActivity(ItemProductSearchResultActivity.class, bundle);
    }

    /**
     * 显示分类字符串
     *
     * @param category
     * @return
     */
    private String calculateCategoryString(ProductCategory category) {
        StringBuffer sb = new StringBuffer();
        if (!category.getName1().isEmpty()) {
            sb.append(category.getName1());
            sb.append(" > ");
        }
        if (!category.getName2().isEmpty()) {
            sb.append(category.getName2());
            sb.append(" > ");
        }
        if (!category.getName3().isEmpty()) {
            sb.append(category.getName3());
            sb.append(" > ");
        }
        if (!category.getName4().isEmpty()) {
            sb.append(category.getName4());
            sb.append(" > ");
        }
        sb.delete(sb.length() - 3, sb.length());
        return sb.toString();
    }
}
